package com.link.base.base.duty.service;

import com.link.base.base.auth.model.Authclient;
import com.link.base.base.auth.service.AuthclientService;
import com.link.base.base.common.dao.mybatis.mapper.MenuMapper;
import com.link.base.base.common.model.InterObject;
import com.link.base.base.common.model.Menu;
import com.link.base.base.common.model.MenuTree;
import com.link.base.base.common.service.MenuService;
import com.link.base.base.duty.dao.mybatis.mapper.DutyMapper;
import com.link.base.base.duty.model.Duty;
import com.link.base.base.duty.model.DutyDto;
import com.link.base.base.duty.model.DutyMenu;
import com.link.base.base.gateway.service.GatewayService;
import com.link.base.base.menupageurls.model.MenuPageUrls;
import com.link.base.base.menupageurls.service.MenuPageUrlsService;
import com.link.base.base.monitor.MonitorObjectChange;
import com.link.base.base.urlinfo.model.UrlDutyLink;
import com.link.base.base.urlinfo.model.UrlInfo;
import com.link.base.base.urlinfo.service.UrlDutyLinkService;
import com.link.base.base.user.model.User;
import com.link.base.user.model.CoreUser;
import com.link.core.basic.dao.KeyGenerateDao;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.ServiceException;
import com.link.core.cllog.LCLogger;
import com.link.core.util.AppConstants;
import com.link.core.util.RedisUtil;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import com.link.core.util.redisclient.LinkRedisClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * Copyright  hande Company. All Rights Reserved.
 *
 * @author unknwon
 * @date: 2018/11/9 16:59
 * @version 1.0
 */

@Service
public class DutyServiceImpl extends BasicServiceImpl<Duty> implements DutyService {

    /**
     * 职责URL的REDISKEY前缀
     */
    public static final String DUTY_URL_KEY_PEX = "DUTY_URL_" ;

    @Resource
    private DutyMapper dutyMapper;

    @Resource
    private MenuService menuService;

    @Resource
    private MenuMapper menuMapper;

    @Resource
    private KeyGenerateDao keyGenerateDao;
    @Resource
    private MonitorObjectChange monitorObjectChange;

    @Resource
    private UrlDutyLinkService urlDutyLinkService;

    @Resource
    private GatewayService gatewayService;

    @Resource
    private MenuPageUrlsService menuPageUrlsService;

    @Resource
    private DutyService dutyService;

    @Resource
    private AuthclientService authclientService;

    @Override
    public BasicMapper<Duty> getBasicMapper() {
        return dutyMapper;
    }

    @Override
    public void beforUpsert(Duty entity) throws Exception {
        if (StringUtils.isBlank(entity.getPlatformType())) {
            throw new ServiceException("DUTY-002");
        }
        super.beforUpsert(entity);
    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void deleteById(Duty entity) throws Exception {
        beforDelete(entity);
        checkId(entity);
        dutyMapper.deleteById(entity);
        dutyMapper.deleteLinkUrlByDutyId(entity);
        dutyMapper.deleteLinkMenuByDutyId(entity);
        dutyMapper.deleteLinkUserByDutyId(entity);
        afterDelete(entity);
        // 当职责被删除后，需要修改职责的url信息
        monitorObjectChange.dutyChange(entity,"CRM_DMS");
    }

    @Override
    public List<Duty> queryDutyListPage(Duty record) throws Exception {
        beforQueryExample(record);
        beforQueryAllOrExample(record);
        return dutyMapper.queryDutyListPage(record);
    }

    @Override
    public List<Menu> queryDutyOfMenuListPage(Menu record) throws Exception {
        return dutyMapper.queryDutyOfMenuListPage(record);
    }

    @Override
    public List<Duty> queryDutyListOfMenu(Menu record) throws Exception {
        return dutyMapper.queryDutyListOfMenuPage(record);
    }

    @Override
    public List<User> queryDutyOfUserListPage(User record) throws Exception {
        return dutyMapper.queryDutyOfUserListPage(record);
    }

    @Override
    public List<Menu> queryUnSelectMenuListPage(Menu record) throws Exception {
        return dutyMapper.queryUnSelectMenuListPage(record);
    }

    @Override
    public List<Duty> queryunSelectDutyOfMenuPage(Duty record) throws Exception {
        return dutyMapper.queryunSelectDutyOfMenuPage(record);
    }

    @Override
    public List<Menu> queryUnSelectSubMenuListPage(Menu record) throws Exception {
        return dutyMapper.queryUnSelectSubMenuListPage(record);
    }

    @Override
    public List<User> queryUnSelectUserListPage(User record) throws Exception {
        return dutyMapper.queryUnSelectUserListPage(record);
    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void addMenuOfDutyInsert(Menu record) throws Exception {
        checkAdminCorp(record, record.getDutyId());
        InterObject interObject = dutyMapper.queryParentMenuExistByMenuOfDuty(record);
        // 查询中间表是否已经插入一级菜单
        if (interObject == null || null == interObject.getId()) {
            record.setAttr6(String.valueOf(keyGenerateDao.keyGenerate()));
            dutyMapper.addParentMenuOfDutyInsert(record);
        }
        record.setAttr5(String.valueOf(keyGenerateDao.keyGenerate()));
        dutyMapper.addMenuOfDutyInsert(record);
        // 给职责添加菜单之后，需要更新职责对应的url信息权限
        Duty duty = new Duty();
        duty.setId(record.getDutyId());
        monitorObjectChange.dutyChange(duty,"CRM_DMS");
    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void addUserOfDutyInsert(User record) throws Exception {
        checkAdminCorp(record, record.getDutyId());
        record.setAttr3(String.valueOf(keyGenerateDao.keyGenerate()));
        dutyMapper.addUserOfDutyInsert(record);
    }

    /**
     * 某种情况下，000账套的登录人员会帮助其他公司账套创建职责的数据，所以
     * 如果当前账套为标准公司账套‘000’，则将职责的账套编号作为新建数据的账套编号
     *
     * @param record
     * @param DutyId
     */
    private void checkAdminCorp(BasicModel record, Long DutyId) {
        try {
//            if (StringUtils.equals(UserUtil.getUser().getCorpid(), AppConstants.ADMIN_CORPID)) {
            if (AppConstants.ADMIN_CORPID.equals(UserUtil.getUser().getCorpid())) {
                // 查询选中的职责信息
                Duty dutyParam = new Duty();
                dutyParam.setId(DutyId);
                Duty duty = queryById(dutyParam);
                record.setLoginCorpId(duty.getCorpid());
                record.setCorpid(duty.getCorpid());
            }
        } catch (Exception e) {
            LCLogger.withException(e);
        }
    }

    @Override
    public void delMenuOfDuty(InterObject record) throws Exception {
        // 根据菜单的row_id查询当前记录，如果是主菜单，则先删除其所有子菜单然后在删除主菜单

        List<Menu> list = dutyMapper.querySecMenuIdListBySecMenuIdAndDutyIdFromMenuOfDuty(record);
        if (list.size() <= 1) {
            dutyMapper.delMenuParentOfDuty(record);
        }
        dutyMapper.delMenuOfDuty(record);
        // 当删除菜单下的关联的职责的时候，当变化时需要触发职责url变化
        Duty duty = new Duty();
        duty.setId(record.getPreObjId());
        monitorObjectChange.dutyChange(duty,"CRM_DMS");
    }

    @Override
    public void delUserOfDuty(InterObject record) throws Exception {
        dutyMapper.delUserOfDuty(record);
    }

    @Override
    public int menuOfDutyUpdate(Menu record) throws Exception {
        if (null == record.getId()) {
            throw new ServiceException("DUTY-003");
        }
        return dutyMapper.menuOfDutyUpdate(record);
    }

    @Override
    public List<UrlInfo> queryUnSelectUrlListPage(UrlInfo record) throws Exception {
        if (StringUtils.isBlank(record.getAttr1())) {
            throw new ServiceException("DUTY-004");
        }
        return dutyMapper.queryUnSelectUrlListPage(record);
    }

    @Override
    public Map<String, Object> menuTreeOfDuty(Menu record) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>(4);
        List<Menu> list = dutyMapper.queryDutyOfMenuListPage(record);
        List<Menu> list1 = new LinkedList<Menu>();
        List<Menu> list2 = new LinkedList<Menu>();
        List<Menu> list3 = new LinkedList<Menu>();
        //将菜单按等级分组
        for (int i = 0; i < list.size(); i++) {
            switch (list.get(i).getMenuGrade()) {
                case "0":
                    list1.add(list.get(i));
                    break;
                case "1":
                    list2.add(list.get(i));
                    break;
                case "2":
                    list3.add(list.get(i));
                    break;
                default:
                    break;
            }
        }
        //为一级菜单进行排序
        Collections.sort(list1, new Comparator<Menu>() {
            @Override
            public int compare(Menu o1, Menu o2) {
                if (o1.getSortNumber() == null) {
                    return -1;
                } else if (o2.getSortNumber() == null) {
                    return 1;
                } else if (o1.getSortNumber() == o2.getSortNumber()) {
                    return 0;
                }
                return o1.getSortNumber().compareTo(o2.getSortNumber()) > 0 ? 1 : -1;
            }
        });
        try {
            //二级菜单权限计算
            list2 = menuService.menuAuthProcessor(list2, null);
            //安全性菜单权限计算
            list3 = menuService.menuAuthProcessor(list3, list2);
            //需要保证菜单顺序
            LinkedHashMap<String, Menu> map = new LinkedHashMap<String, Menu>(list2.size());
            LinkedHashMap<String, Object>[] temp = new LinkedHashMap[list1.size()];
            //为每一个一级菜单寻找对应的二级菜单
            for (int k = 0; k < list1.size(); k++) {
                temp[k] = new LinkedHashMap<String, Object>();

                //二级菜单合并，权限最终确定
                for (int i = 0; i < list2.size(); i++) {
                    Menu menu = list2.get(i);
                    String menuId = menu.getId().toString();
                    Menu mapMenu = map.get(menuId);

                    String parentMenuId = menu.getParentMenuId() != null ? menu.getParentMenuId().toString() : "noMacthId";
                    if (parentMenuId.equals(list1.get(k).getAttr1())) {
                        if (mapMenu == null) {
                            map.put(menu.getAttr1(), menu);
                        } else {
                            menuService.menuAuthMerge(menu, mapMenu);
                        }
                    }
                }

                //安全性菜单合并，权限最终确定，并设置到二级菜单下
                for (int i = 0; i < list3.size(); i++) {
                    Menu subMenu = list3.get(i);
                    if (subMenu.getParentMenuId() != null) {
                        String subParentId = subMenu.getParentMenuId().toString();
                        Menu menu = map.get(subParentId);
                        if (menu == null) {
                            continue;
                        }
                        if (menu.getSubMenus() != null) {
                            menuService.menuAuthMerge(subMenu, menu.getSubMenus());
                        } else {
                            List<Menu> subMenus = new ArrayList<Menu>();
                            subMenus.add(subMenu);
                            menu.setSubMenus(subMenus);
                        }
                    }
                }
                list = new ArrayList<Menu>(map.values());
                map.clear();
                temp[k].put("level1", list1.get(k));
                temp[k].put("level2", list);
            }
            result.put("result", temp);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
        }

        return result;

    }

    @Override
    public List<Menu> queryMenuByDutyId(Menu record) throws Exception {
        return dutyMapper.queryMenuByDutyId(record);
    }


    /**
     * 给当前职责添加菜单及安全性菜单
     * 先删除当前职责下的所有菜单及安全性菜单
     * @param record
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void addMenuAndSubMenuOfDuty(DutyMenu record) throws Exception {
        Long dutyId = record.getDutyId();
        List<Menu> menus = record.getMenuList();
        /*删除当前职责下的所有菜单及安全性菜单*/
        InterObject interObject = new InterObject();
        interObject.setPreObjId(dutyId);
        dutyMapper.delAllMenuOfDuty(interObject);

        /*加菜单及安全性菜单*/
        if (menus.size() > 0) {
            menus.forEach(menuObj -> {
                try {
                    /*菜单*/
                    Menu menu = new Menu();
                    menu.setDutyId(dutyId);
                    menu.setId(menuObj.getId());
                    addMenuOfDutyInsert(menu);
                    /*安全性菜单*/
                    Menu subMenu = new Menu();
                    subMenu.setParentMenuId(menuObj.getId());
                    subMenu.setPageFlag(false);
                    List<Menu> subMenuList = menuMapper.queryByExamplePage(subMenu);
                    if (subMenuList.size() > 0) {
                        subMenuList.forEach(subMenu1 -> {
                            try {
                                Menu menu1 = new Menu();
                                menu1.setDutyId(dutyId);
                                menu1.setId(subMenu1.getId());
                                addMenuOfDutyInsert(menu1);
                            } catch (Exception e) {
                                LCLogger.withException(e);
                                throw new ServiceException(e.getMessage());
                            }
                        });
                    }
                } catch (Exception e) {
                    LCLogger.withException(e);
                    throw new ServiceException(e.getMessage());
                }
            });
        }
    }

    /**
     * 删除职责：删除用户下的职责
     *
     * @param record
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void delDutyByUserId(InterObject record) throws Exception {
        dutyMapper.delDutyByUserId(record);
    }

    /**
     * 查询未被当前url关联的职责列表
     *
     * @author yaojiangyi
     * @date 2019/02/28 16:53
     * @param record 职责
     */
    @Override
    public List<Duty> queryunSelectDutyOfUrlPage(Duty record) throws Exception {
        return dutyMapper.queryunSelectDutyOfUrlPage(record);
    }

    @Override
    public void saveQuickSafetyMenuDuty(MenuTree entity) throws Exception {
        List<MenuTree> newList = entity.getNewList();
        //删掉当前职责下所有关联的菜单
        InterObject interObject = new InterObject();
        interObject.setPreObjId(entity.getDutyId());
        dutyMapper.delAllMenuOfDuty(interObject);
        Set<Long> headMenuId = new HashSet<>();
        List<MenuTree> newDealList = dealSafetyMenuDutyList(newList, entity, headMenuId);
        if (newDealList.isEmpty()) {
            return;
        }
        List<MenuTree> addEndList = new ArrayList<>();
        CoreUser user = UserUtil.getUser();
        // 插入安全性菜单
        for (MenuTree menuTree : newDealList) {
            MenuTree record = new MenuTree();
            record.setId(keyGenerateDao.keyGenerate());
            record.setCreatedBy(user.getId());
            record.setLastUpdatedBy(user.getId());
            record.setCorpid(user.getCorpid());
            record.setMenuId(menuTree.getSafetyCheckId());
            record.setDutyId(menuTree.getDutyId());
            addEndList.add(record);
        }
        /* 插入一级菜单和二级菜单
         *  本快捷操作针对同一职责下的菜单和安全性进行操作，故所有dutyId为同一个，此处取第一个
         *  */
        Long dutyId = newDealList.get(0).getDutyId();
        for (Long item : headMenuId) {
            MenuTree record = new MenuTree();
            record.setId(keyGenerateDao.keyGenerate());
            record.setCreatedBy(user.getId());
            record.setLastUpdatedBy(user.getId());
            record.setCorpid(user.getCorpid());
            record.setMenuId(item);
            record.setDutyId(dutyId);
            addEndList.add(record);
        }
        int num = 500;
        int count = addEndList.size() / num;
        for (int i = 0; i < count + 1; i++) {
            if (i == count) {
                dutyMapper.insertQuickSafetyDutyMenu(addEndList.subList(i * num, addEndList.size()));
            } else {
                dutyMapper.insertQuickSafetyDutyMenu(addEndList.subList(i * num, (i + 1) * num));
            }
        }


    }

    @Override
    public List<DutyDto> queryUsersDutyListPage( DutyDto t) throws Exception {
        beforQueryExample(t);
        beforQueryAllOrExample(t);
        return dutyMapper.queryUsersDutyListPage(t);
    }

    private List<MenuTree> dealSafetyMenuDutyList(List<MenuTree> menuTreeList, MenuTree entity, Set<Long> headMenuId) {
        List<MenuTree> resultList = new ArrayList<>();
        if (menuTreeList.isEmpty()) {
            return new ArrayList<>();
        }
        for (MenuTree record : menuTreeList) {
            if (CollectionUtils.isEmpty(record.getSafetyCheckList())) {
                continue;
            }
            headMenuId.add(record.getId());
            headMenuId.add(record.getParentMenuId());
            for (String safetyCheckId : record.getSafetyCheckList()) {
                MenuTree safetyOne = new MenuTree();
                safetyOne.setDutyId(entity.getDutyId());
                safetyOne.setSafetyCheckId(Long.parseLong(safetyCheckId));
                resultList.add(safetyOne);
            }
        }
        return resultList;
    }

    /**
     * 刷新用户所有职责
     *
     * @author 黄龙建
     * @date 2020年07月03日
     */
    @Override
    public void refreshPermissions() throws Exception {
        try {
            Duty dutyQuery = new Duty();
            CoreUser user = UserUtil.getUser();
            dutyQuery.setLoginCorpId(user.getCorpid());
            dutyQuery.setPageFlag(false);
            dutyQuery.setCorpid(user.getLoginCorpId());
            List<Duty> dutyList = this.queryByExamplePage(dutyQuery);

            //把已经被删掉的职责从redis里面清楚
            for (Duty duty : dutyList) {
                this.refreshPermByDutyId(duty);
            }
        } catch (Exception e) {
            throw e;
        }
    }


    /**
     * 刷新一个职责的权限
     *
     * @author 黄龙建
     * @date 2020年07月03日
     */
    @Override
    public void refreshPermByDutyId(Duty duty) throws Exception {
        LinkRedisClient jedis = null;
        try {
            Long id = duty.getId();
            if (id == null) {
                throw new Exception("职责id不能为空！");
            }
            jedis = RedisUtil.getJedis();
            //查询出当前职责信息。
            Duty dutyRet = dutyMapper.queryById(duty);
            if (dutyRet == null) {
                //如果当前职责不存在，则直接删除其对应的redis中的key
                jedis.del(DUTY_URL_KEY_PEX.concat("CRM".concat("_").concat(String.valueOf(id))).toUpperCase());
                gatewayService.refreshAllCache("duty:".concat(DUTY_URL_KEY_PEX
                        .concat("CRM".concat("_").concat(String.valueOf(id))).toUpperCase()));

                jedis.del(DUTY_URL_KEY_PEX.concat("DMS".concat("_").concat(String.valueOf(id))).toUpperCase());
                gatewayService.refreshAllCache("duty:".concat(DUTY_URL_KEY_PEX
                        .concat("DMS".concat("_").concat(String.valueOf(id))).toUpperCase()));

                jedis.del(DUTY_URL_KEY_PEX.concat("API".concat("_").concat(String.valueOf(id))).toUpperCase());
                gatewayService.refreshAllCache("duty:".concat(DUTY_URL_KEY_PEX
                        .concat("API".concat("_").concat(String.valueOf(id))).toUpperCase()));
                return;
            }

            MenuPageUrls menuPageUrlsQuery = new MenuPageUrls();
            menuPageUrlsQuery.setDutyId(duty.getId());
            List<String> urlDutyUrlList = menuPageUrlsService.getUrlsByDuty(menuPageUrlsQuery);

            //获取得到相关的rediskey
            String keyPreStr = dutyRet.getPlatformType();
            //为了统一，key都设置成大写的。
            String redisKey = DUTY_URL_KEY_PEX.concat(keyPreStr.concat("_").concat(String.valueOf(id))).toUpperCase();
            //先删除原有的
            jedis.del(redisKey);

            //把数据放入到一个数组中去。批量插入Redis中。
            String[] urlDutyUrlArray = new String[urlDutyUrlList.size()];
            urlDutyUrlList.toArray(urlDutyUrlArray);
            if (urlDutyUrlArray.length > 0) {
                jedis.lpush(redisKey, urlDutyUrlArray);
            }
            gatewayService.refreshAllCache("duty:".concat(redisKey));
        } finally {
            RedisUtil.returnResource(jedis);
        }
    }

    @Override
    public void refreshPermissionsNew() throws Exception {
        LinkRedisClient jedis = RedisUtil.getJedis();
        try {
            Duty duty = new Duty();
            CoreUser user = UserUtil.getUser();
            duty.setLoginCorpId(user.getCorpid());
            duty.setPageFlag(false);
            duty.setCorpid(user.getLoginCorpId());
            List<Duty> dutyList = this.queryByExamplePage(duty);


            //把已经被删掉的职责从redis里面清楚
            deleteNoUseDutyFromRedis(dutyList, "duty_url");
            deleteNoUseDutyFromRedis(dutyList, "duty_clientid");
            deleteNoUseDutyFromRedis(dutyList, "duty_username");

            for (Duty dutyTmp : dutyList) {


                QueryParams qps = new QueryParams();
                qps.addFilter(new Filter("dutyId", String.valueOf(dutyTmp.getId())));
                qps.setPageFlag(false);
                User t = BasicModel.transformClass(User.class, qps);
                List<User> userList = dutyService.queryDutyOfUserListPage(t);


                UrlDutyLink urlDutyLink = BasicModel.transformClass(UrlDutyLink.class, qps);
                urlDutyLink.setAccessFlag("Y");
                List<UrlDutyLink> urlDutyLinkList = urlDutyLinkService.queryByExamplePage(urlDutyLink);

                Authclient authclientQuery = new Authclient();
                authclientQuery.setDutyId(dutyTmp.getId());
                List<Authclient> authclientList = authclientService.queryClientByDutyPage(authclientQuery);

                //考虑到同一时间只有一个用户操作，所以不考虑线程安全
                StringBuilder userNames = new StringBuilder();
                userNames.append(",");
                for (User userTemp : userList) {
                    userNames.append(userTemp.getUsername()).append(",");
                }

                StringBuilder linkUrlBuild = new StringBuilder();
                linkUrlBuild.append(",");
                for (UrlDutyLink dutyLink : urlDutyLinkList) {
                    linkUrlBuild.append(dutyLink.getUrl()).append(",");
                }

                StringBuilder clientBuild = new StringBuilder();
                clientBuild.append(",");
                for (Authclient authclient : authclientList) {
                    clientBuild.append(authclient.getClientId()).append(",");
                }

                //只对关联了用户和url的职责进行处理
                if (userNames.length() > 1 && linkUrlBuild.length() > 1) {
                    //不用删除，直接覆盖。
                    jedis.hset("duty_username", String.valueOf(dutyTmp.getId()), userNames.toString());
                    jedis.hset("duty_url", String.valueOf(dutyTmp.getId()), linkUrlBuild.toString());
                }

                if (clientBuild.length() > 1) {
                    if (linkUrlBuild.length() > 1) {
                        //不用删除，直接覆盖。
                        jedis.hset("duty_clientid", String.valueOf(dutyTmp.getId()), clientBuild.toString());
                        jedis.hset("duty_url", String.valueOf(dutyTmp.getId()), linkUrlBuild.toString());
                    } else {
                        //不用删除，直接覆盖。
                        jedis.hset("duty_clientid", String.valueOf(dutyTmp.getId()), clientBuild.toString());
                        jedis.hset("duty_url", String.valueOf(dutyTmp.getId()), "");
                    }
                }
            }
            gatewayService.refreshAllCache("duty");
        } catch (Exception e) {
            throw new Exception(e);
        } finally {
            RedisUtil.returnResource(jedis);
        }
    }

    /**
     * @author HuangLJ
     * @date 2019-07-25 14:09
     * @param dutyList 所有职责的列表
     * @param keyName 要清楚的key的名字
     * @throws Exception 报错
     * 把职责权限中，已经在表中被删掉的key在redis中也删除掉
     */
    private void deleteNoUseDutyFromRedis(List<Duty> dutyList, String keyName) throws Exception {
        LinkRedisClient jedis = RedisUtil.getJedis();
        try {
            //把已经被删掉的职责从redis里面清楚
            Set<String> dutyIdRedis = jedis.hkeys(keyName);
            for (String id : dutyIdRedis) {
                for (Duty duty : dutyList) {
                    String dutyId = String.valueOf(duty.getId());
                    if (!id.equals(dutyId)) {
                        break;
                    }
                }
                jedis.hdel(keyName, id);
            }
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        } finally {
            RedisUtil.returnResource(jedis);
        }
    }

    /**
     * 当删除一个职责之后，刷新其职责权限信息
     *
     * @author 黄龙建
     * @date 2020年07月23日
     */
    @Override
    public void afterDelete(Duty duty) throws Exception {
        this.refreshPermByDutyId(duty);
    }
}
